package com.lxh.student.service.impl;

import com.lxh.student.entity.ResponseResult;
import com.lxh.student.entity.Teacher;
import com.lxh.student.entity.TeacherDetails;
import com.lxh.student.service.TeacherService;
import com.lxh.student.utils.JwtUtil;
import com.lxh.student.utils.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author lxh
 * @date 2023/4/5 14:02
 */

@Service("teacherLoginServiceImpl")
@Slf4j
public class TeacherLoginServiceImpl implements TeacherService {

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult findOne(Teacher teacher) {
        log.info("TeacherLoginServiceImpl");
        //1.使用ProviderManager auth方法进行验证
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(teacher.getName(), teacher.getPassword());
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        //2.校验失败
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或者密码错误！");
        }
        log.info("密码校验成功");
        //3.校验成功 生成jwt给前端
        TeacherDetails teacherDetails = (TeacherDetails) (authenticate.getPrincipal());
        Long id = teacherDetails.getTeacher().getId();
        String jwt = JwtUtil.createJWT(id.toString());
        Map<String,String> map=new HashMap();
        map.put("token",jwt);
        //4. 存到redis中
        redisCache.setCacheObject("teacher:login:"+id,teacherDetails);
        return new ResponseResult(200,"登陆成功！",map);
    }

    @Override
    public Teacher findOne(String username) {
        return null;
    }

    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        TeacherDetails teacherDetails = (TeacherDetails) authentication.getPrincipal();
        Long id = teacherDetails.getTeacher().getId();
        boolean deleteSuccess = redisCache.deleteObject("teacher:login:" + id);
        if (!deleteSuccess){
            return new ResponseResult(410,"用户信息redis已过期");
        }
        return new ResponseResult(200,"退出成功！");
    }
}
